'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sententialyzer.settings import SENTENTIALYZER_DEFAULT_GROUP_NAME
from sent.utils import createValidToken, CommonResult, ErrorIds, AccessToken
from sent.utils.result_printer import getPrinter
import re
from sent.model.entities.opinion import Opinion, OpinionEvaluations
from sent.model.OpinionDBManager import OpinionDBManager

groupPermissionRegex = re.compile(r"^([a-zA-Z0-9_\+\=\/\.\,\\\!\@\#\$\%\^\&\*\(\)]+):([rcd]+)$")

class CreateBaseOpinion(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        accessTokenStr = self.request.POST.get('access_token', None)
        title = self.request.POST.get('title', '')
        content = self.request.POST.get('content', '')
        opinion_data = self.request.POST.get('opinion_data', '')
        group_permissions = self.request.POST.get('group_permissions', None)
        
        cResult = CommonResult()
        
        if accessTokenStr and title and group_permissions and content:
            
            accessToken, error = createValidToken(accessTokenStr, 'bopin_c')
            if accessToken:
                groupPermissionsList = group_permissions.split(' ')
                assert isinstance(accessToken, AccessToken)
                validPermissions = True
                groupPermissionsDict = {}
                for groupPermission in groupPermissionsList:
                    m = groupPermissionRegex.match(groupPermission)
                    if m:
                        groupId = m.group(1)
                        permissions = set(m.group(2))
                        groupPermissionsDict[groupId] = permissions
                    else:
                        validPermissions = False
                        break
                
                if validPermissions:
                    dbMan = OpinionDBManager(False)
                    try:
                        opinion = Opinion()
                        opinion.setCreatorIdString(accessToken.owner_id)
                        opinion.evaluation = OpinionEvaluations.NEUTRAL
                        
                        opinion.external_data = unicode(opinion_data)
                        opinion.title = unicode(title)
                        opinion.textData = unicode(content)
                        #opinion.default_perm = groupPermissionsDict.pop(SENTENTIALYZER_DEFAULT_GROUP_NAME, '')
                        defaultPerm = groupPermissionsDict.get(SENTENTIALYZER_DEFAULT_GROUP_NAME, [])
                        opinion.default_perm = "".join(defaultPerm)
                        
                        if not opinion.containsDefaultScope('d'):
                            dbMan.createBaseOpinion(opinion)
                            
                            dbMan.addBaseOpinionPermissions(opinion.id, groupPermissionsDict)
                            
                            cResult.result = opinion.toPrimitiveDict()
                            
                            dbMan.commitSession()
                            
                            cResult.errorId = ErrorIds.SUCCESS
                        else:
                            dbMan.dbSession.rollback()
                            cResult.errorId = ErrorIds.BADREQUEST
                            cResult.result = "Permission 'd' not allowed for the default group"
                    except:
                        dbMan.dbSession.rollback()
                        raise
                    finally:
                        dbMan.closeSession()
                else:
                    cResult.errorId = ErrorIds.BADREQUEST
                    cResult.result = "Invalid group permissions"
                    
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult)
    
    